package cn.iocoder.yudao.module.product.controller.admin.spu;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServerException;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.product.api.property.dto.ProductPropertyValueDetailRespDTO;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.*;
import cn.iocoder.yudao.module.product.convert.spu.ProductSpuConvert;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyDO;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyValueDO;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.product.enums.property.PropertyValueTypeEnum;
import cn.iocoder.yudao.module.product.enums.spu.*;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
import cn.iocoder.yudao.module.product.service.spu.IESimSpuService;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.pojo.PageParam.PAGE_SIZE_NONE;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 商品 SPU")
@RestController
@RequestMapping("/product/spu")
@Validated
@Slf4j
public class ProductSpuController {

    @Resource
    private ProductSpuService productSpuService;
    @Resource
    private ProductSkuService productSkuService;
    @Resource
    private ProductPropertyValueService productPropertyValueService;
    @Resource
    private IESimSpuService eSimSpuService;

    @PostMapping("/create")
    @Operation(summary = "创建商品 SPU")
    @PreAuthorize("@ss.hasPermission('product:spu:create')")
    public CommonResult<Long> createProductSpu(@Valid @RequestBody ProductSpuSaveReqVO createReqVO) {
        checkCreateOrUpdateSpu(createReqVO);
        return success(productSpuService.createSpu(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新商品 SPU")
    @PreAuthorize("@ss.hasPermission('product:spu:update')")
    public CommonResult<Boolean> updateSpu(@Valid @RequestBody ProductSpuSaveReqVO updateReqVO) {
        checkCreateOrUpdateSpu(updateReqVO);
        productSpuService.updateSpu(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新商品 SPU Status")
    @PreAuthorize("@ss.hasPermission('product:spu:update')")
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody ProductSpuUpdateStatusReqVO updateReqVO) {
        productSpuService.updateSpuStatus(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除商品 SPU")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:spu:delete')")
    public CommonResult<Boolean> deleteSpu(@RequestParam("id") Long id) {
        productSpuService.deleteSpu(id);
        return success(true);
    }

    @GetMapping("/get-detail")
    @Operation(summary = "获得商品 SPU 明细")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:spu:query')")
    public CommonResult<ProductSpuRespVO> getSpuDetail(@RequestParam("id") Long id) {
        // 获得商品 SPU
        ProductSpuDO spu = productSpuService.getSpu(id);
        if (spu == null) {
            return success(null);
        }

        // 查询上架状态的商品 SKU
        List<ProductSkuDO> skus = productSkuService.selectListBySpuIdAndStatus(ProductSkuStatusEnum.ENABLE, Arrays.asList(spu.getId()));

        // 转换vo
        ProductSpuRespVO spuRespVO = ProductSpuConvert.INSTANCE.convert(spu, skus);

        // 查询SPU基础属性
        final List<ProductPropertyValueDetailRespDTO> spuProperty = productPropertyValueService.getSpuProperty(PropertyValueTypeEnum.SPU, id);
        if (CollUtil.isNotEmpty(spuProperty)){
            final List<ProductSpuSaveReqVO.Property> properties = spuProperty.stream().map(v -> BeanUtils.toBean(v, ProductSpuSaveReqVO.Property.class)).collect(Collectors.toList());
            spuRespVO.setProperties(properties);
        }

        return success(spuRespVO);
    }


    @GetMapping("/list-all-simple")
    @Operation(summary = "获得商品 SPU 精简列表")
    @PreAuthorize("@ss.hasPermission('product:spu:query')")
    public CommonResult<List<ProductSpuSimpleRespVO>> getSpuSimpleList() {
        List<ProductSpuDO> list = productSpuService.getSpuListByStatus(ProductSpuStatusEnum.ENABLE.getStatus());
        // 降序排序后，返回给前端
        list.sort(Comparator.comparing(ProductSpuDO::getSort).reversed());
        return success(BeanUtils.toBean(list, ProductSpuSimpleRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得商品 SPU 详情列表")
    @Parameter(name = "spuIds", description = "spu 编号列表", required = true, example = "[1,2,3]")
    @PreAuthorize("@ss.hasPermission('product:spu:query')")
    public CommonResult<List<ProductSpuRespVO>> getSpuList(@RequestParam("spuIds") Collection<Long> spuIds) {
        return success(ProductSpuConvert.INSTANCE.convertForSpuDetailRespListVO(
                productSpuService.getSpuList(spuIds), productSkuService.getSkuListBySpuId(spuIds)));
    }

    @RequestMapping(value = "/page", method = {RequestMethod.GET})
    @Operation(summary = "获得商品 SPU 分页")
    @PreAuthorize("@ss.hasPermission('product:spu:query')")
    public CommonResult<PageResult<ProductSpuRespVO>> getSpuPage(@Valid ProductSpuPageReqVO pageVO) {
        PageResult<ProductSpuDO> pageResult = productSpuService.getSpuPage(pageVO);
        return success(BeanUtils.toBean(pageResult, ProductSpuRespVO.class));
    }

    @GetMapping("/get-count")
    @Operation(summary = "获得商品 SPU 分页 tab count")
    @PreAuthorize("@ss.hasPermission('product:spu:query')")
    public CommonResult<Map<Integer, Long>> getSpuCount() {
        return success(productSpuService.getTabsCount());
    }

    @GetMapping("/export")
    @Operation(summary = "导出商品")
    @PreAuthorize("@ss.hasPermission('product:spu:export')")
    @OperateLog(type = EXPORT)
    public void exportSpuList(@Validated ProductSpuPageReqVO reqVO,
                               HttpServletResponse response) throws IOException {
        reqVO.setPageSize(PAGE_SIZE_NONE);
        List<ProductSpuDO> list = productSpuService.getSpuPage(reqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "商品列表.xls", "数据", ProductSpuRespVO.class,
                BeanUtils.toBean(list, ProductSpuRespVO.class));
    }

    // ========== 新增 =========

    private void checkCreateOrUpdateSpu(ProductSpuSaveReqVO createReqVO) {
        // 检查货币单位
        checkCurrencyCode(createReqVO);

        // 检查商品轮播图
        checkSliderPicUrls(createReqVO);

        // 检查配送方式
        checkDeliveryType(createReqVO);

        // 检查虚拟商品参数
        checkVirtualProduct(createReqVO);
    }

    /**
     * 检查虚拟商品参数
     * @param createReqVO
     */
    private void checkVirtualProduct(ProductSpuSaveReqVO createReqVO){
        if (createReqVO.getVirtualProduct()) {
            // 虚拟商品
            checkFieldNullable(createReqVO.getId(), createReqVO, "productType");

            final ProductTypeEnum productTypeEnum = ProductTypeEnum.fromValue(createReqVO.getProductType());
            if (productTypeEnum == ProductTypeEnum.GIFT_CARD){
                // 礼品卡
                checkFieldNullable(createReqVO.getId(), createReqVO, "rechargeMethod");

                // 检查自定义用户输入框
                checkCustomUserInput(createReqVO);

                // 检查sku
                if (CollUtil.isNotEmpty(createReqVO.getSkus())){
                    for (ProductSkuSaveReqVO sku : createReqVO.getSkus()) {
                        checkFieldNullable(createReqVO.getId(), sku, "deliveryMethod"); // 发货方式
                        checkFieldNullable(createReqVO.getId(), sku, "customDenomination"); // 是否自定义面值
                        checkFieldNullable(createReqVO.getId(), sku, "cardKeyProductNo"); // 卡密商品编号
                        if (sku.getCustomDenomination()){
                            // 自定义面额
                            checkFieldNullable(createReqVO.getId(), sku, "minCustomDenomination"); // 最小自定义面值
                            checkFieldNullable(createReqVO.getId(), sku, "maxCustomDenomination"); // 最大自定义面值
                        }
                    }
                }
            }
        }
    }

    private void checkFieldNullable(Long id, Object object, String fieldName){
        final Object fieldValue = ReflectUtil.getFieldValue(object, fieldName);
        if (fieldValue == null || (fieldValue instanceof String && StrUtil.isEmpty((String) fieldValue))) {
            log.warn("字段为空, id = {}, fieldName = {}, fieldValue = {}", id, fieldName, fieldValue);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_NULL_ERROR, fieldName);
        }
    }

    /**
     * 检查货币单位
     * @param createReqVO
     */
    private void checkCurrencyCode(ProductSpuSaveReqVO createReqVO){
        final String currencyCode = createReqVO.getCurrencyCode();
        final CurrencyUnitEnum currencyUnitEnum = CurrencyUnitEnum.fromValue(currencyCode);
        if (currencyUnitEnum == null){
            log.warn("未知的货币单位, spuId = {}, currencyCode = {}, currencyUnitEnum = {}",
                    createReqVO.getId(), currencyCode, currencyUnitEnum);
            throw new ServerException(ErrorCodeConstants.SPU_CURRENCY_CODE_ERROR);
        }
    }

    /**
     * 检查配送方式
     * @param createReqVO
     */
    private void checkDeliveryType(ProductSpuSaveReqVO createReqVO){
        final List<Integer> deliveryTypes = createReqVO.getDeliveryTypes();
        for (Integer deliveryType : deliveryTypes) {
            if (!inDeliveryTypeEnum(deliveryType)) {
                log.warn("配送方式错误, spuId = {}, deliveryType = {}, deliveryTypes = {}",
                        createReqVO.getId(), deliveryType, deliveryTypes);
                throw new ServerException(ErrorCodeConstants.SPU_DELIVERY_TYPE_ERROR);
            }
        }
    }

    private boolean inDeliveryTypeEnum(Integer num) {
        for (int value : DeliveryTypeEnum.ARRAYS) {
            if (num.equals(value)){
                return true;
            }
        }
        return false;
    }

    /**
     * 检查商品轮播图
     * @param createReqVO
     */
    private void checkSliderPicUrls(ProductSpuSaveReqVO createReqVO) {
        final List<String> sliderPicUrls = createReqVO.getSliderPicUrls();
        if (CollUtil.isNotEmpty(sliderPicUrls)){
            for (String url : sliderPicUrls){
                if (StrUtil.isEmpty(url)){
                    log.warn("商品轮播图不能为空, spuId = {}, url = {}, sliderPicUrls = {}",
                            createReqVO.getId(), url, sliderPicUrls);
                    throw new ServerException(ErrorCodeConstants.SPU_SLIDER_NULL);
                }
            }
        }
    }

    /**
     * 检查自定义用户输入框
     * @param createReqVO
     */
    private void checkCustomUserInput(ProductSpuSaveReqVO createReqVO) {
        final List<Integer> customUserInput = createReqVO.getCustomUserInput();
        if (CollUtil.isNotEmpty(customUserInput)){
            for (Integer input : customUserInput) {
                if (!inCustomUserInputEnum(input)) {
                    log.warn("自定义用户输入框错误, spuId = {}, input = {}, customUserInput = {}",
                            createReqVO.getId(), input, customUserInput);
                    throw new ServerException(ErrorCodeConstants.SPU_CUSTOM_USER_INPUT_ERROR);
                }
            }
        }
    }

    private boolean inCustomUserInputEnum(Integer num) {
        for (int value : CustomUserInputEnum.ARRAYS) {
            if (num.equals(value)){
                return true;
            }
        }
        return false;
    }

    @PostMapping("/create-from-es-product")
    @Operation(summary = "从eSim商品创建商品 SPU")
    @PreAuthorize("@ss.hasPermission('product:spu:create')")
    public CommonResult<Void> createProductSpuFromEsProduct() {
        eSimSpuService.createSpuFromEsProduct();
        return success(null);
    }

}
